package com.tanhua.management.interceptor;

import com.tanhua.common.utils.NoAuthorization;
import com.tanhua.management.pojo.Admin;
import com.tanhua.management.service.AdminService;

import com.tanhua.management.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限认证
 * 过滤器,访问前判断token是否合法
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

     @Autowired
    private AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //先将线程池中map集合里存的user清空
        //应为线程池中线程有限,所以会导致重复利用线程
        UserThreadLocal.set(null);
        //校验handler是否是HandlerMethod
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //判断是否包含@NoAuthorization注解，如果包含，直接放行
        if (((HandlerMethod) handler).hasMethodAnnotation(NoAuthorization.class)) {
            return true;
        }

        String token = request.getHeader("Authorization");
        token = token.replace("Bearer ", "");
        Admin admin = adminService.queryUserByToken(token);
        if (null == admin) {
            response.setStatus(401);//无权限
            return false;
        }
        //将用户对象保存在当前线程
        UserThreadLocal.set(admin);
        return true;
    }
}
